<!--密码强度-->
<template>
  <el-popover
    placement="right"
    width="270"
    trigger="click">
    <div :style="{ width: '240px' }" class="password-level-container">
      <div :class="[passwordLevelClass]" class="level-info">强度：<span>{{ passwordLevelName }}</span></div>
      <el-progress :percentage="state.percent" :show-text="false" :color="passwordLevelColor" class="level-progress" />
      <div class="level-tips">
        <span>请至少输入 8 个字符。请不要使用容易被猜到的密码。</span>
      </div>
    </div>
    <el-input slot="reference" v-model="password" type="password" :maxlength="maxlength" show-password show-word-limit autocomplete="off" :placeholder="placeholder" />
  </el-popover>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '至少8位密码，区分大小写'
    },
    maxlength: {
      type: Number,
      default: 16
    }
  },
  data() {
    return {
      password: '',
      state: {
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      levelNames: {
        0: '低',
        1: '低',
        2: '中',
        3: '强'
      },
      levelClass: {
        0: 'color-danger',
        1: 'color-danger',
        2: 'color-warning',
        3: 'color-primary'
      },
      levelColor: {
        0: '#FC5E65',
        1: '#FC5E65',
        2: '#FEAB3F',
        3: '#4a5dff'
      }
    }
  },
  computed: {
    passwordLevelClass() {
      return this.levelClass[this.state.passwordLevel]
    },
    passwordLevelName() {
      return this.levelNames[this.state.passwordLevel]
    },
    passwordLevelColor() {
      return this.levelColor[this.state.passwordLevel]
    }
  },
  watch: {
    password: function(val) {
      this.handlePasswordLevel(val)
      this.$emit('input', val)
    },
    value: function(val) {
      this.password = val
    }
  },
  methods: {
    handlePasswordLevel(value) {
      let level = 0
      // 判断这个字符串中有没有数字
      if (this.$validate._hasNumber(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (this.$validate._hasBigChar(value) && this.$validate._hasSmallChar(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
      }
    }
  }
}
</script>
<style lang="scss">
  .password-level-container{
    .level-info{
      font-size: 14px;
      line-height: 1.5;
    }
    .level-progress{
      margin: 10px 0;
    }
    .level-tips{
      margin-top: 10px;
      line-height: 1.5;
    }
  }
</style>
